#include "SList.h"

SLT* BuySLT(int x)
{
	SLT* newnode = (SLT*)malloc(sizeof(SLT));
	newnode->data = x;
	newnode->next = NULL;
	return newnode;
}
void SLTPushBack(SLT** phead, int x)
{
	SLT* newnode = BuySLT(x);
	if (*phead == NULL)
	{
		*phead = newnode;
	}
	else
	{
		SLT* tail = *phead;
		while (tail->next != NULL)
		{
			tail = tail->next;
		}
		tail->next = newnode;
	}
}

void SListPrint(SLT* phead)
{
	SLT* cur = phead;
	while (cur != NULL)
	{
		printf("%d->", cur->data);
		cur = cur->next;
	}
	printf("NULL\n");
}

void SLTPushFront(SLT** phead, int x)
{
	SLT* newnode = BuySLT(x);
	newnode->next = *phead;
	*phead = newnode;
}

void SLTpopBack(SLT** phead)
{
	if (*phead == NULL)
	{
		return;
	}
	if ((*phead)->next == NULL)
	{
		free(*phead);
		*phead = NULL;
		return;
	}
	SLT* tail = *phead;
	SLT* pf = NULL;
	while (tail->next != NULL)
	{
		pf = tail;
		tail = tail->next;
	}
	free(tail);
	tail = NULL;
	pf->next = NULL;
}

void SLTpopFront(SLT** phead)
{
	if (*phead == NULL)
	{
		return;
	}
	SLT* next = (*phead)->next;
	free(*phead);
	*phead = next;
}

SLT* SLTFind(SLT* phead, int x)
{
	SLT* cur = phead;
	while (cur)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void SLTInsert(SLT** phead,SLT* pos ,int x)
{
	SLT* prev = *phead;
	while (prev->next != pos)
	{
		prev = prev->next;
	}
	SLT* newnode = (SLT*)malloc(sizeof(SLT));
	newnode->data = x;
	prev->next = newnode;
	newnode->next = pos;
}

void SLTErase(SLT** phead, SLT* pos)
{
	if (pos == *phead)
	{
		SLTpopFront(phead);
	}
	else
	{
		SLT* cur = *phead;
		while (cur->next != pos)
		{
			cur = cur->next;
		}
		cur->next = pos->next;
		free(pos);
		pos = NULL;
	}
}
